/******************************************************************************/
package jamie.org.sil.www.UsxVernacularCreator;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;

import jamie.org.sil.www.usxUtils.*;


/******************************************************************************/
/**
 * All information which is specific to the vernacularParms file.  (A concrete
 * realisation of XmlDetails.)
 * <p>
 *
 * Note that the order in which tags are added to the data structures here
 * determines the order in which they will be written out to the XML file.
*/

public class XmlDetailsVernacularAdditional extends XmlDetails
{
  /****************************************************************************/
  /****************************************************************************/
  /**                                                                        **/
  /**                               Public                                   **/
  /**                                                                        **/
  /****************************************************************************/
  /****************************************************************************/


  /****************************************************************************/
  /** Constructor.
   *
   * @throws RuntimeException
   */

  public XmlDetailsVernacularAdditional () throws RuntimeException
  {
  }


  /****************************************************************************/
  /** Returns the root tag to be used when writing the output file.
   *
   * @return Root tag.
   */

  @Override public String getRootTag ()
  {
    return "vernacularParmsMiscellaneous";
  }


  /****************************************************************************/
  /** Gets the names to be applied to the tabs on the tabbed pane.
   *
   * @return names
   */

  @Override final public String[] getTabNames ()
  {
    String s[] = {"General information"};
    return s;
  }


  /****************************************************************************/
  /** Initialises the instance.  We need to carry this out as a separate step
   *  because it relies on the availability of information which can be
   *  supplied only after the instance has been created.
   */

  @Override public void initialise ()
  {
    String[] tabNames = getTabNames();
    for (int i = 0; i < tabNames.length; ++i)
      m_PerTabTagTable.put(i, new ArrayList<ConfigTag.Generic>(100));

    doTagsGeneral();    
  }


  /****************************************************************************/
  /**
   * Validates the current output.  (No need to check that mandatory items have
   * been supplied -- that's handled elsewhere.)
   *
   * @return A tag to which focus is transferred if an error is detected.
   */

  @Override public ConfigTag.Generic validate ()
  {
    /**************************************************************************/
    m_ValidationErrors = "";



    /**************************************************************************/
    /* Check if the output folder already exists. */

    String iso = ((String) m_OverallTagTable.get("-iso").getValue()).toUpperCase();
    String rootFolder = (String) m_OverallTagTable.get("-rootFolder").getValue();
    if (!rootFolder.endsWith("/") && !rootFolder.endsWith("\\")) rootFolder += "/";
    if ((new File(rootFolder + iso)).exists())
    {
      m_ValidationErrors = "A folder for this vernacular already exists.  Please delete it manually if you wish to replace it.";
      return m_OverallTagTable.get("-iso");
    }




    /**************************************************************************/
    /* Check that the vernacularParms file really does look like one. */

    String vernacularParmsFile = (String) m_OverallTagTable.get("-vernacularParmsFile").getValue();
    boolean ok = false;
    try
    {
      BufferedReader reader = new BufferedReader(new FileReader(vernacularParmsFile));
      String line  = null;
      while ( ( line = reader.readLine() ) != null )
      {
        ok = -1 != line.indexOf("<vernacularParms>");
        if (ok) break;
      }
    }
    catch (Exception e)
    {
    }

    if (!ok)
    {
      m_ValidationErrors = "That doesn't look like a vernacularParms file.";
      return m_OverallTagTable.get("-vernacularParmsFile");
    }


    /**************************************************************************/
    /* Check that we have at least one .SFM file in the Usx folder. */

    ok = false;
    String[] matchingFiles =
      Utils.getFileNamesInFolder((String) m_OverallTagTable.get("-UsxInputFolder").getValue(), "¬", false).split("\\¬");
    for (int i = 0; i < matchingFiles.length; ++i)
    {
      ok = matchingFiles[i].toLowerCase().endsWith(".sfm");
      if (!ok) break;
    }

    if (!ok)
    {
      m_ValidationErrors = "The Usx input folder contains no .SFM files, or at least one non-.SFM file.";
      return m_OverallTagTable.get("-UsxInputFolder");
    }




    /**************************************************************************/
    /* If we're checking versification, we must know the versification details
     * against which to validate.
     */

    String versification = (String) XmlDetails.instance().getTag("versificationScheme").getValue();
    boolean checkVersification = (Boolean) XmlDetails.instance().getTag("checkVersification").getValue();
    if (checkVersification && 0 == versification.length())
    {
      m_ValidationErrors = "If you're asking for versification to be checked, you must supply versification details.";
      return m_OverallTagTable.get("versification");
    }



    /**************************************************************************/
    return null;
  }






  /****************************************************************************/
  /****************************************************************************/
  /**                                                                        **/
  /**                               Private                                  **/
  /**                                                                        **/
  /****************************************************************************/
  /****************************************************************************/

  /****************************************************************************/
  /* Add details of Dublin Core tags. */

  private void doTagsGeneral () throws RuntimeException
  {
    setTabNo("General information");

    addTag(new ConfigTag.Header("File locations ..."));

    String rootFolder = (new File(".")).getAbsolutePath();
    if (0 != XmlDetails.instance().getProductionRootPath().length())
      rootFolder = XmlDetails.instance().getProductionRootPath();
    else if (rootFolder.endsWith("/_Java"))
      rootFolder = rootFolder.substring(0, rootFolder.indexOf("/_Java"));
    else
      rootFolder = "C:/SilProduction";

    addTag(new ConfigTag.Folder("-rootFolder",
                                "Root folder for output",
                                "Root folder for output (the one which contains the vernacular subfolders)",
                                rootFolder,
                                ConfigTag.Optionality.C_Mandatory));

    addTag(new ConfigTag.Folder("-UsxInputFolder",
                                "Usx input folder",
                                "Folder containg Usx text files supplied by translator",
                                "",
                                ConfigTag.Optionality.C_Mandatory));

    addTag(new ConfigTag.File("-vernacularParmsFile",
                              "Vernacular parms file",
                              "File containing vernacular-specific information supplied by translator",
                              "",
                              ConfigTag.Optionality.C_Mandatory));

    addTag(new ConfigTag.Folder("-peripheralsFolder",
                                "Folder containing peripheral files",
                                "If supplied, this folder must be structured in the 'standard' way for peripherals.",
                                "",
                                ConfigTag.Optionality.C_Optional));

    addTag(new ConfigTag.Folder("-imagesFolder",
                                "Folder containing images",
                                "",
                                "",
                                ConfigTag.Optionality.C_Optional));
  }
}
